package net.yebaihe.wc.QQ;

import net.yebaihe.wc.R;
import net.yebaihe.wc.SNS;
import net.yebaihe.wc.QQ.utils.TokenStore;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.OAuthClient;

/**
 * main activity to access qweibo api 
 */

public class OAuthActivity extends Activity {

	private OAuth oauth;
	private OAuthClient auth;
	//public String picPath = "/mnt/sdcard/PhotoSola/1309793574239.jpg";
	public String picPath = "/mnt/sdcard/mydesert.jpg";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sns_sina);		
	}
	
	/**
	 * call back from qweibo page
	 */
	public void onResume() {
		super.onResume();
		
		Uri uri = this.getIntent().getData();

		if(uri != null) {
			String oauth_verifier = uri.getQueryParameter("oauth_verifier");	
			String oauth_token = uri.getQueryParameter("oauth_token");	
			
			getToken(oauth_verifier, oauth_token);
		}
	}	
	
	/**
	 * get token from verifier code
	 * @param oauth_verifier
	 * @param oauth_token
	 */
	public void getToken(String oauth_verifier, String oauth_token) {
		oauth = SNS.oauth;
		auth = SNS.auth;
		
		oauth.setOauth_verifier(oauth_verifier);
		oauth.setOauth_token(oauth_token);
		
		try {
			oauth = auth.accessToken(oauth);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (oauth.getStatus() == 2) {
			System.out.println("Get Access Token failed!");
			return;
		} else {			
			// 已经拿到access token，可以使用oauth对象访问所有API了
			// 将access token存储到SharedPreferences里
			TokenStore.store(this, oauth);
			Toast.makeText(this, "腾讯微博认证成功！", Toast.LENGTH_SHORT).show();
			TextView txtHint=(TextView) OAuthActivity.this.findViewById(R.id.txtHint);
			txtHint.setText("账户已关联，按 返回键 返回主程序!");
		}
	}
}
